<template>
	<el-card style="width: 100%">
		<el-form label-width="80px" size="small">
			<el-upload class="avatar-uploader" :action="serverIp+'/file/upload'" :show-file-list="false"
				:on-success="handleAvatarSuccess">
				<img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar" />
				<i v-else class="el-icon-plus avatar-uploader-icon"></i>
			</el-upload>

			<el-form-item label="用户名">
				<el-input v-model="form.username" disabled autocomplete="off"></el-input>
			</el-form-item>
			<el-form-item label="昵称">
				<el-input v-model="form.nickname" autocomplete="off"></el-input>
			</el-form-item>
			<el-form-item label="头像">
				<el-input v-model="form.avatarUrl" autocomplete="off"></el-input>
			</el-form-item>
			<el-form-item label="邮箱">
				<el-input v-model="form.email" autocomplete="off"></el-input>
			</el-form-item>
			<el-form-item label="电话">
				<el-input v-model="form.phone" autocomplete="off"></el-input>
			</el-form-item>
			<el-form-item label="地址">
				<el-input type="textarea" v-model="form.address" autocomplete="off"></el-input>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" @click="save">确 定</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>

<script>
	import {serverIp} from "../../common/config.js";
	export default {
		data() {
			return {
				form: {},
				user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
				serverIp: serverIp
			};
		},
		created() {
			this.getUser().then(res => {
				console.log("getUser", res)
				this.form = res
			})
		},
		methods: {
			async getUser() {
				return (await this.request.get("/user/username/" + this.user.username)).data;
			},

			save() {
				this.request.post("/user", this.form).then((res) => {
					if (res.code === "200") {
						this.$message.success("保存成功");

						uni.switchTab({
							url: '/pages/news/my'
						})
						setTimeout(res => {
							location.reload()
						}, 2000)

						//更新浏览器存储的用户信息
						// 这段代码的作用是更新浏览器存储的用户信息中的 token，
						// 并将更新后的用户信息重新存储到浏览器中。这样做的目的可能是为了确保用户信息的准确性和及时性。
						this.getUser().then((res) => {
							res.token = JSON.parse(localStorage.getItem("user")).token;
							localStorage.setItem("user", JSON.stringify(res));
							console.log("token", res)
						});
					} else {
						this.$message.error("保存失败");
					}
				});
			},
			// 获取文件
			handleAvatarSuccess(res) {
				console.log("avatarUrl", res)
				this.form.avatarUrl = res;
			}
		},
	};
</script>

<style>
	.avatar-uploader {
		text-align: center;
		padding-bottom: 10px;
	}

	.avatar {
		width: 158px;
		height: 158px;
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 158px;
		height: 158px;
		line-height: 158px;
		text-align: center;
		border: 1px #ccc solid;
	}
</style>
